package com.fg.cloud.manager.service.product.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.construction.ResultMap;
import com.fg.cloud.common.construction.ResultSelect;
import com.fg.cloud.common.construction.Select;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.common.tuple.ThreeTuple;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyVo;
import com.fg.cloud.manager.entry.order.vo.OrderDetailEntityMorUnitVo;
import com.fg.cloud.manager.entry.product.ProductInfoEntity;
import com.fg.cloud.manager.entry.product.ProductMoreUnitEntity;
import com.fg.cloud.manager.entry.product.vo.ProductAllDataVo;
import com.fg.cloud.manager.entry.product.vo.ProductInfoVo;
import com.fg.cloud.manager.entry.product.vo.ProductSkuImgAndParamAllDateVo;
import com.fg.cloud.manager.entry.product.vo.ProductSkuVo;
import com.fg.cloud.manager.entry.product.vo.UnitVo;
import com.fg.cloud.manager.entry.system.StockEntity;
import com.fg.cloud.manager.mapper.agency.AgencyMapper;
import com.fg.cloud.manager.mapper.product.AgencyProductHomeMapper;
import com.fg.cloud.manager.service.product.AgencyProductHomeService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 
 * Description:AgencyProductHomeServiceimpl
 * @author 陈银龙
 * @date 2017年8月22日下午4:04:13
 */
@Service
public class AgencyProductHomeServiceimpl implements AgencyProductHomeService{

	@Autowired
	private AgencyProductHomeMapper AgencyProductServiceHomeimpl;
	@Autowired
	private AgencyMapper agencyMapper;
	
	public List<ProductInfoVo> toList(List<ProductAllDataVo> rs){
		ProductInfoVo product = null;
		ProductSkuVo sku = null;
		
		//返回结果集
		List<ProductInfoVo> list = new ArrayList<ProductInfoVo>();
		//封装唯一商品头
		Map<Long, ProductInfoVo> productMap = new HashMap<Long, ProductInfoVo>();
		
		Map<Long, List<ResultSelect>> resultSpecMap = new HashMap<Long, List<ResultSelect>>();
		List<ResultSelect> resultSpecList = null;
		Map<Long, List<ResultMap>> resultSkuMap = new HashMap<Long, List<ResultMap>>();
		List<ResultMap> resultSkuList = null;
		
		//sku对应多单位集合，key=skuId
		Map<Long, List<UnitVo>> unitMap = new HashMap<Long, List<UnitVo>>();
		Map<String, String> tempSkuMap = null;
		
		List<UnitVo> unitList = null;
		List<Long> productIdList = new ArrayList<Long>();

		ThreeTuple<ProductInfoVo, ProductSkuVo, UnitVo> tempData = null;
		
		for (int i = 0; i < rs.size(); i++) {
			ResultMap resultSku = null;
			String skuKey = null, skuTempKey = null;
			tempData = convert(rs.get(i));
			//取唯一Product
			if (null == productMap.get(tempData.a.getId())) product = tempData.a;
			else product = productMap.get(tempData.a.getId());
			//取product对应的List<ResultSelect>
			if (null == resultSpecMap.get(product.getId())) resultSpecList = Lists.newArrayList();
			else resultSpecList = resultSpecMap.get(product.getId());
			//取product对应的List<ResultMap>
			if (null == resultSkuMap.get(product.getId())) resultSkuList = Lists.newArrayList();
			else resultSkuList = resultSkuMap.get(product.getId()) ;
			
			//取Product对应的SKU信息，不为空取老值绑定，为空取当前新记录
			if (StringUtils.isNotEmpty(tempData.b.getProductSpec())) {
				//处理规格信息包装问题
				skuTempKey = setSpecMap(resultSpecList, tempData.b.getProductSpec(), tempData.b.getIsDefault());
				skuKey = skuTempKey.replaceAll(",", "");
				resultSku = new ResultMap(skuKey);
				//绑定SKU对象
				if (resultSkuList.contains(resultSku)) {
					for (int j = 0; j < resultSkuList.size(); j++) {
						if(skuKey.equals(resultSkuList.get(j).getLabel())) {
							resultSku = resultSkuList.get(j);
							break;
						}
					}
					sku = (ProductSkuVo) resultSku.getValue();
				} else {
					sku = tempData.b;
				}
			} else {
				sku = tempData.b;
			}
			
			//取多单位信息
			if (null == unitMap.get(sku.getId())) {
				unitList = Lists.newArrayList();
				//当不存在多单位时，将当前详情ID插入多单位首
				unitList.add(new UnitVo(sku.getUnitId(), sku.getUnitName(), 1, sku.getSpecialPrice()));
			} else unitList = unitMap.get(sku.getId());
			
			//插入最新多单位信息，只存在有值和null
			if(null != tempData.c.getId()) {
				unitList.add(tempData.c);
			}
			
			//封装多单位
			unitMap.put(sku.getId(), unitList);
			sku.setUnitList(unitList);
			
			//当为默认时，设置价格信息，后续自行判断折扣率等问题
			if (1 == sku.getIsDefault()) {
				/*product.setDiscountPrice(null == sku.getSpecialPrice() ? 
						sku.getProductPrice() : sku.getSpecialPrice());
				product.setUnitId(sku.getUnitId());
				product.setUnitName(sku.getUnitName());
				product.setUnitNum(1);
				product.setDefaultSkuId(sku.getId());
				product.setStock(sku.getStock());
				product.setStockContent(sku.getStockContent());*/
				product.setImg(sku.getSkuImage());
				if (StringUtils.isNotEmpty(skuTempKey)) {
					List<Map<String, String>> defaultSku = new ArrayList<Map<String, String>>();
					if(skuTempKey != null){
						for (String temp : skuTempKey.split(",")) {
							tempSkuMap = Maps.newHashMap();
							tempSkuMap.put("value", temp);
							defaultSku.add(tempSkuMap);
						}
					}
					product.setDefaultSku(defaultSku);
					/*List<Map<String, String>> defaultSku = product.getDefaultSku();
					  if(defaultSku.size()==0){
						for (String temp : skuTempKey.split(",")) {
							tempSkuMap = Maps.newHashMap();
							tempSkuMap.put("value", temp);
							defaultSku.add(tempSkuMap);
						}
					 }*/
				}
				//product.setUnitList(unitList);
				product.setSku(sku);
			}
			
			//封装sku对象
			if (null != skuKey) {
				resultSku.setValue(sku);
				if(!resultSkuList.contains(resultSku)) resultSkuList.add(resultSku);
				resultSkuMap.put(product.getId(), resultSkuList);
			}
			product.setResultSkuList(resultSkuList);
			
			//封装spec
			resultSpecMap.put(product.getId(), resultSpecList);
			product.setResultSpecList(resultSpecList);
			//封装SKU记录
			//if (StringUtils.isEmpty(skuKey)) product.setSku(sku);
			productMap.put(product.getId(), product);
			if (!productIdList.contains(product.getId())) {
				list.add(product);
				productIdList.add(product.getId());
			}
			productMap.put(product.getId(), product);
			if (!productIdList.contains(product.getId())) {
				list.add(product);
				productIdList.add(product.getId());
			}
			
			// 如果没有默认规格,则把当前规格放入默认规格
			List<Map<String, String>> defaultSku = product.getDefaultSku();
			  if(defaultSku.size()==0){
				  /*product.setDiscountPrice(null == sku.getSpecialPrice() ? 
					sku.getProductPrice() : sku.getSpecialPrice());
					product.setUnitId(sku.getUnitId());
					product.setUnitName(sku.getUnitName());
					product.setUnitNum(1);
					product.setDefaultSkuId(sku.getId());
					product.setStock(sku.getStock());
					product.setStockContent(sku.getStockContent());*/
					product.setImg(sku.getSkuImage());
				if(skuTempKey != null){
					for (String temp : skuTempKey.split(",")) {
						tempSkuMap = Maps.newHashMap();
						tempSkuMap.put("value", temp);
						defaultSku.add(tempSkuMap);
					}
				}
				//product.setUnitList(unitList);
				product.setSku(sku);
			 }
		}
		return list;
	}
	
	/**
	 * Description:多规格封装处理
	 * @param resultSpecList
	 * @param specs
	 * @return String sku组合key
	 * @author around
	 * @date 2017年8月21日下午3:58:41
	 */
	private String setSpecMap(List<ResultSelect> resultSpecList, String specs, Integer defult) {
		//正则表达式，不懂查
		String[] specArray = specs.split("[:,]+");
		//获取当前规格对象对应的规格信息组合
		String specKey = "";
		ResultSelect resultSpec = null;
		List<Select> selectSet = null;
		Select select = null;
		Boolean falag = false;
		if(defult == 1){
			falag = true;
		}
		//按格式化结构规律迭代规格明细，拆封封装到指定集合
		for (int i = 0; i < specArray.length; i+=2) {
			resultSpec = new ResultSelect(specArray[i]);
			if (resultSpecList.contains(resultSpec)) {
				for (int j = 0; j < resultSpecList.size(); j++) {
					if (resultSpec.equals(resultSpecList.get(j))) {
						resultSpec = resultSpecList.get(j);
						select = new Select(specArray[i+1],specArray[i+1],falag);
						if (!resultSpec.getValue().contains(select)){
							resultSpec.getValue().add(select);
						}else if(falag == true){
							resultSpec.getValue().remove(select);
							resultSpec.getValue().add(select);
						}
						break;
					}
				}
			} else {
				selectSet = Lists.newArrayList();
				selectSet.add(new Select(specArray[i+1],specArray[i+1],falag));
				resultSpec.setValue(selectSet);
				resultSpecList.add(resultSpec);
			}
			specKey += specArray[i+1]+",";
		}
		return specKey;
	}
	
	
	/**
	 * Description:自定义多对象封装
	 * @param data
	 * @return ThreeTuple
	 * @author around
	 * @date 2017年8月20日下午3:49:39
	 */
	private ThreeTuple<ProductInfoVo, ProductSkuVo, UnitVo> convert(
			ProductAllDataVo data) {
		AgencyUserVo user = (AgencyUserVo) UserUtils.getCurrentUser();
		
		ProductInfoVo product = new ProductInfoVo();
		product.setId(data.getId());
		product.setFacId(data.getFacId());
		product.setProductName(data.getProductName());
		product.setImg(data.getImg());
		product.setIsConmodity(data.getIsConmodity());
		product.setIsNewProduct(data.getIsNewProduct());
		product.setIsPerformence(data.getIsPerformence());
		product.setIsStandard(data.getIsStandard());
		product.setCategoryName(data.getCategoryName());
		product.setCollection(data.getCollection());
		product.setIsCustom(0);
		String spec = data.getProductSpec();
		if(data.getProductSpec()!=null){
			product.setSpec(spec.replace("{", "【").replace("}", "】"));
		}else{
			product.setSpec(spec);
		}
		
		List<String> iconList = product.getIconList();
		if (1 == data.getIsNewProduct()) iconList.add("新");
		if (1 == data.getIsConmodity()) iconList.add("热");
		if (1 == data.getIsPerformence()) iconList.add("高");
		
		ProductSkuVo sku = new ProductSkuVo();
		sku.setId(data.getSkuId());
		sku.setUnitId(data.getUnitId());
		sku.setUnitName(data.getUnitName());
		sku.setUnitNum(1);
		sku.setProductPrice(data.getProductPrice());
		sku.setSpecialPrice(data.getSpecialPrice());
		sku.setStock(data.getStock());
		sku.setBarcode(data.getBarcode());
		sku.setProductSpec(data.getProductSpec());
		sku.setIsDefault(data.getIsDefault());
		sku.setIsGround(data.getIsGround());
		sku.setProductNumber(data.getProductNumber());
		sku.setSkuImage(data.getProductImg());
		sku.setShowPrice(data.getProductPrice());
		//处理库存问题
		getStockContent(user.getStockSetup(), sku);

		UnitVo unit = new UnitVo();
		unit.setId(data.getConversionUnitId());
		unit.setName(data.getConversionUnitName());
		unit.setBaseUnitId(data.getStandardUnitId());
		unit.setNum(data.getConversionNum());
		//unit.setCustomPrice(data.getCustomPrice());
		//处理商品SKU实际价格问题及多单位中价格问题
		if (null == sku.getSpecialPrice()) {
			sku.setSpecialPrice(sku.getProductPrice().multiply(
					BigDecimal.valueOf(user.getDiscount().doubleValue()*0.01)));
			if(data.getConversionUnitId() != null){
				unit.setCustomPrice(data.getCustomPrice().multiply(
						BigDecimal.valueOf(user.getDiscount().doubleValue()*0.01)));
			}
		} else {
			if(data.getConversionUnitId() != null){
				unit.setCustomPrice(sku.getSpecialPrice().multiply(
						BigDecimal.valueOf(data.getConversionNum())));
			}
		}
		
		return new ThreeTuple<ProductInfoVo, ProductSkuVo, UnitVo>(product,sku,unit);
	}

	@Override
	public void findBySenior(PageUtils<ProductInfoVo> pageinfo) {
		AgencyUserVo user = (AgencyUserVo) UserUtils.getCurrentUser();
		//user.setId(null);
		Long count;
		if(user.getId() == null){
			count = AgencyProductServiceHomeimpl.findSeniorCountByVisitor(pageinfo);
		}else{
			if(user.getPlaceorder() == 1){
				count = AgencyProductServiceHomeimpl.findSeniorCount(pageinfo);
			}else{
				count = AgencyProductServiceHomeimpl.findSeniorCountByVisitor(pageinfo);
			}
		}
		pageinfo.setTotal(count);
		
		if (count == 0) {
			pageinfo.setData(new ArrayList<ProductInfoVo>());
			return;
		}
		
		List<ProductAllDataVo> rs;
		if(user.getId() == null){
			rs = AgencyProductServiceHomeimpl.findSeniorByVisitor(pageinfo);
		}else{
			//user.setPlaceorder(1);
			if(user.getPlaceorder() == 1){
				rs = AgencyProductServiceHomeimpl.findBySenior(pageinfo);
			}else{
				rs = AgencyProductServiceHomeimpl.findProductsForPlaceorder(pageinfo);
			}
		}
		
		/*Long count = AgencyProductServiceHomeimpl.findSeniorCount(pageinfo);
		pageinfo.setTotal(count);
		if (count == 0) {
			pageinfo.setData(new ArrayList<ProductInfoVo>());
			return;
		}
		List<ProductAllDataVo> rs = AgencyProductServiceHomeimpl.findBySenior(pageinfo);*/
		pageinfo.setData(toList(rs));
	}
	
	private void getStockContent(StockEntity stock, ProductSkuVo sku) {
		if(1 == stock.getDisplayFlag()) {
			if (0 == stock.getNumFlag()) {
				if (null != sku.getStock()) {
					if (1 <= sku.getStock().compareTo(BigDecimal.valueOf(stock.getMaxBorder())))
						sku.setStockContent(stock.getMaxPrompt());
					else if (1 <= sku.getStock().compareTo(BigDecimal.valueOf(stock.getMinBorder())))
						sku.setStockContent(stock.getMiddlePrompt());
					else
						sku.setStockContent(stock.getMinPrompt());
				} else {
					sku.setStockContent("未知");
				}
			}
		}
	}

	@Override
	public ProductInfoVo findParamAndImg(Map<String, Object> usmap) {
		AgencyUserVo user = (AgencyUserVo) UserUtils.getCurrentUser();
		// 查出商品头和规格信息,parm集合
		//user.setId(null);
		ProductInfoVo rs = AgencyProductServiceHomeimpl.findByProductId(usmap);
		if(rs == null){
			return null;
		}
		// 查出规格信息和多单位,图片集合
		List<ProductSkuImgAndParamAllDateVo> list;
		if(user.getId() == null){//游客
			list = AgencyProductServiceHomeimpl.findParamAndImgByVisitor(usmap);
		}else{
			list = AgencyProductServiceHomeimpl.findParamAndImg(usmap);
		}
		List<UnitVo> unitList = new ArrayList<UnitVo>();//商品上总的多单位
		List<ResultSelect> resultSpecList = new ArrayList<ResultSelect>();//规格信息
		List<ResultMap> resultSkuList = Lists.newArrayList();//规格组合
		List<String> iconList = rs.getIconList();
		if (1 == rs.getIsNewProduct()) iconList.add("新");
		if (1 == rs.getIsConmodity()) iconList.add("热");
		if (1 == rs.getIsPerformence()) iconList.add("高");
		
			
		Map<Long, ProductSkuVo> skumap = new HashMap<Long, ProductSkuVo>();//规格详情
		//Map<Long, UnitVo> unitmap = new HashMap<Long, UnitVo>();
		Map<Long, List<UnitVo>> unitmap = new HashMap<Long, List<UnitVo>>();// 用于存放每个规格的多单位
		//Map<Long, ProductSkuImgEntity> imgmap = new HashMap<Long, ProductSkuImgEntity>();
		//Map<Long, List<ProductSkuImgEntity>> imgmap = new HashMap<Long, List<ProductSkuImgEntity>>();// 每个规格的多图
		ProductSkuVo sku1 = null;//存放规格
		String skuKey = null, skuTempKey = null;
		ResultMap resultSku = null;
		Set<Long> unitidSet = new LinkedHashSet<Long>();
		//Set<Long> imgidSet = new HashSet<Long>();
		Map<String, String> tempSkuMap = null;
		List<String> imgs = new ArrayList<String>();// 多图
		Set<String> imgSet = new HashSet<String>();
			for(int i = 0;i<list.size();i++){
				if(null != list.get(i).getUrl() && imgSet.add(list.get(i).getUrl())){
					imgs.add(list.get(i).getUrl());// 多图
				}
				//多sku
				ProductSkuVo sku = new ProductSkuVo();
				sku.setId(list.get(i).getSkuId());
				sku.setUnitId(list.get(i).getUnitId());
				sku.setUnitName(list.get(i).getUnitName());
				sku.setUnitNum(1);
				sku.setProductPrice(list.get(i).getProductPrice());
				sku.setSpecialPrice(list.get(i).getSpecialPrice());
				sku.setStock(list.get(i).getStock());
				sku.setBarcode(list.get(i).getBarcode());
				sku.setShowPrice(list.get(i).getProductPrice());
				if(list.get(i).getProductSpec()!=null){
					sku.setProductSpec(list.get(i).getProductSpec().replace("{", "【").replace("}", "】"));
				}else{
					sku.setProductSpec(list.get(i).getProductSpec());
				}
				sku.setIsDefault(list.get(i).getIsDefault());
				sku.setIsGround(list.get(i).getIsGround());
				sku.setProductNumber(list.get(i).getProductNumber());
				sku.setSkuImage(list.get(i).getProductImg());
				//处理库存问题
				getStockContent(user.getStockSetup(), sku);
				skumap.put(list.get(i).getSkuId(), sku);
				
				//多单位
				UnitVo unit = new UnitVo();
				//unit.setSkuId(list.get(i).getSkuId());
				unit.setId(list.get(i).getConversionUnitId());
				//处理前端看到的多单位名称
				unit.setName(list.get(i).getConversionUnitName() + 
						"(" + list.get(i).getConversionNum() + sku.getUnitName() + ")");
				unit.setBaseUnitId(list.get(i).getStandardUnitId());
				unit.setNum(list.get(i).getConversionNum());
				
				//处理商品SKU实际价格问题及多单位中价格问题
				if (null == sku.getSpecialPrice()) {
					sku.setSpecialPrice(sku.getProductPrice().multiply(
							BigDecimal.valueOf(user.getDiscount().doubleValue()*0.01)));
					if(list.get(i).getConversionUnitId() != null){
						unit.setCustomPrice(list.get(i).getCustomPrice().multiply(
								BigDecimal.valueOf(user.getDiscount().doubleValue()*0.01)));
					}
				} else {
					if(list.get(i).getConversionUnitId() != null){
						unit.setCustomPrice(sku.getSpecialPrice().multiply(
								BigDecimal.valueOf(list.get(i).getConversionNum())));
					}
				}
				//多图
				/*ProductSkuImgEntity pi = new ProductSkuImgEntity();
				pi.setId(list.get(i).getImgId());
				pi.setSkuId(list.get(i).getSkuId());
				pi.setUrl(list.get(i).getUrl());*/
				
				//取Product对应的SKU信息，不为空取老值绑定，为空取当前新记录
				if (StringUtils.isNotEmpty(list.get(i).getProductSpec())) {
					//处理规格信息包装问题
					skuTempKey = setSpecMap(resultSpecList, list.get(i).getProductSpec(),list.get(i).getIsDefault());
					skuKey = skuTempKey.replaceAll(",", "");
					resultSku = new ResultMap(skuKey);
					//绑定SKU对象
					if (resultSkuList.contains(resultSku)) {
						for (int j = 0; j < resultSkuList.size(); j++) {
							if(skuKey.equals(resultSkuList.get(j).getLabel())) {
								resultSku = resultSkuList.get(j);
								break;
							}
						}
						sku1 = (ProductSkuVo) resultSku.getValue();
					} else {
						sku1 = sku;
					}
				} else {
					sku1 = sku;
				}
				//封装sku对象
				if (null != skuKey) {
					resultSku.setValue(sku1);
					if(!resultSkuList.contains(resultSku)) resultSkuList.add(resultSku);
				}

				// 多图封装
				//List<ProductSkuImgEntity> imgs = imgmap.get(list.get(i).getSkuId()) == null ? new ArrayList<ProductSkuImgEntity>() :imgmap.get(list.get(i).getSkuId());
				/*for(int p = 0;p< imgs.size();p++){
					imgidSet.add(imgs.get(p).getId());
				}
				if(pi.getId() != null && imgidSet.add(pi.getId())){
					imgs.add(pi);
				}
				imgmap.put(list.get(i).getSkuId(), imgs);*/
				
				// 多单位封装
				List<UnitVo> units = unitmap.get(list.get(i).getSkuId()) == null ? new ArrayList<UnitVo>() :unitmap.get(list.get(i).getSkuId());
				if(units.size() == 0){
					units.add(new UnitVo(sku1.getUnitId(),sku1.getUnitName(),1, sku.getSpecialPrice()));
				}
				for(int p = 0;p< units.size();p++){
					unitidSet.add(units.get(p).getId());
				}
				if(unit.getId() != null && unitidSet.add(unit.getId())){
					units.add(unit);
					unitList.add(unit);
				}
				unitmap.put(list.get(i).getSkuId(), units);
				
				//封装多单位
				sku1.setUnitList(unitmap.get(list.get(i).getSkuId()));
				
				//插入图
				//sku1.setImgList(imgmap.get(list.get(i).getSkuId()));
				
				//当为默认时，设置价格信息，后续自行判断折扣率等问题
				if (1 == sku1.getIsDefault()) {
					rs.setSku(sku1);
					/*rs.setDiscountPrice(null == sku1.getSpecialPrice() ? 
							sku1.getProductPrice() : sku1.getSpecialPrice());
					rs.setUnitId(sku1.getUnitId());
					rs.setUnitName(sku1.getUnitName());
					rs.setUnitNum(1);
					rs.setUnitList(sku1.getUnitList());
					rs.setSpec(sku1.getProductSpec());
					rs.setDefaultSkuId(sku1.getId());
					rs.setStock(sku1.getStock());
					rs.setStockContent(sku1.getStockContent());*/
					if (StringUtils.isNotEmpty(skuTempKey)) {
						List<Map<String, String>> defaultSku = rs.getDefaultSku();
						if(defaultSku.size()==0){
							for (String temp : skuTempKey.split(",")) {
								tempSkuMap = Maps.newHashMap();
								tempSkuMap.put("value", temp);
								defaultSku.add(tempSkuMap);
							}
						}
					}
				}
				//封装sku对象
				if (i == list.size()-1 && null == rs.getSku()) {
					rs.setSku(sku1);
				}
			}
			// 添加默认多单位
			//unitList.add(new UnitVo(sku1.getUnitId(),sku1.getUnitName(),1));
			rs.setIsCustom(0);
			rs.setImgList(imgs);
			rs.setResultSkuList(resultSkuList);
			rs.setResultSpecList(resultSpecList);
			return rs;
	}

	@Override
	public void findBuy(PageUtils<ProductInfoEntity> pageinfo) {
		Long count = AgencyProductServiceHomeimpl.findBuyCount(pageinfo);
		pageinfo.setTotal(count);
		if(count>0){
			
			Set<Long> idSet = new HashSet<Long>();
			List<ProductInfoEntity> list = new ArrayList<ProductInfoEntity>();
			List<ProductInfoEntity> list1 = AgencyProductServiceHomeimpl.findBuy(pageinfo);
			for(int i = 0; i<list1.size();i++){
				if(idSet.add(list1.get(i).getId())){
					list.add(list1.get(i));
				}
			}
			pageinfo.setData(list);
		}else{
			pageinfo.setData(new ArrayList<ProductInfoEntity>());
		}
	}

	@Override
	public void findWeCharBySenior(PageUtils<ProductInfoVo> pageinfo) {
		/*Long count = AgencyProductServiceHomeimpl.findWeCharBySeniorCount(pageinfo);
		pageinfo.setTotal(count);
		if (count == 0) {
			pageinfo.setData(new ArrayList<ProductInfoVo>());
			return;
		}
		List<ProductInfoVo> rs = AgencyProductServiceHomeimpl.findWeCharBySenior(pageinfo);*/
		
		AgencyUserVo user = (AgencyUserVo) UserUtils.getCurrentUser();
		//user.setId(null);
		Long count;
		if(user.getId() == null){
			count = AgencyProductServiceHomeimpl.findWeCharBySeniorCountVisitor(pageinfo);
		}else{
			if(user.getPlaceorder() == 1){
				count = AgencyProductServiceHomeimpl.findWeCharBySeniorCount(pageinfo);
			}else{
				count = AgencyProductServiceHomeimpl.findWeCharBySeniorCountVisitor(pageinfo);
			}
		}
		pageinfo.setTotal(count);
		
		if (count == 0) {
			pageinfo.setData(new ArrayList<ProductInfoVo>());
			return;
		}
		
		List<ProductInfoVo> rs;
		if(user.getId() == null){
			rs = AgencyProductServiceHomeimpl.findWeCharBySeniorVisitor(pageinfo);
		}else{
			if(user.getPlaceorder() == 1){
				rs = AgencyProductServiceHomeimpl.findWeCharBySenior(pageinfo);
			}else{
				rs = AgencyProductServiceHomeimpl.findWeCharBySeniorVisitorForPlaceorder(pageinfo);
			}
		}
		
		for(int i = 0;i<rs.size();i++){
			List<String> iconList = rs.get(i).getIconList();
			if (1 == rs.get(i).getIsNewProduct()) iconList.add("新");
			if (1 == rs.get(i).getIsConmodity()) iconList.add("热");
			if (1 == rs.get(i).getIsPerformence()) iconList.add("高");
			rs.get(i).setIconList(iconList);
			rs.get(i).setIsCustom(0);
			if(rs.get(i).getSpec()!=null){
				rs.get(i).setSpec(rs.get(i).getSpec().replace("{", "【").replace("}", "】"));
			}else{
				rs.get(i).setSpec(rs.get(i).getSpec());
			}
			
			/*if(rs.get(i).getSpecialPrice() == null){
				rs.get(i).setSpecialPrice(rs.get(i).getProductPrice().multiply(
						BigDecimal.valueOf(user.getDiscount().doubleValue()*0.01)));
			}*/
		}
		pageinfo.setData(rs);
	}

	@Override
	public void findByCategory(PageUtils<OrderDetailEntityMorUnitVo> pageinfo,String source) {
		Long count = AgencyProductServiceHomeimpl.findByCategoryCount(pageinfo);
		pageinfo.setTotal(count);
		if (count == 0) {
			pageinfo.setData(new ArrayList<OrderDetailEntityMorUnitVo>());
			return;
		}
		
		List<OrderDetailEntityMorUnitVo> rsresult = new ArrayList<OrderDetailEntityMorUnitVo>();// 用于装返回数据
		List<OrderDetailEntityMorUnitVo> rs = AgencyProductServiceHomeimpl.findByCategory(pageinfo);
		
		Map<Long, OrderDetailEntityMorUnitVo> resultMap = new HashMap<Long, OrderDetailEntityMorUnitVo>();
		Map<Long, List<ProductMoreUnitEntity>> morunitMap = new HashMap<Long, List<ProductMoreUnitEntity>>();
		//封装多单位
		for(int i = 0; i<rs.size();i++){
			OrderDetailEntityMorUnitVo ov = rs.get(i);
			
			if(ov.getProductSpec()!=null){
				ov.setProductSpec(rs.get(i).getProductSpec().replace("{", "【").replace("}", "】"));
			}else{
				ov.setProductSpec(rs.get(i).getProductSpec());
			}
			
			BigDecimal discount = new BigDecimal(0);
			if("factory".equals(source)){
				Long ageId = Long.parseLong(pageinfo.getCondition().get("ageId").toString());
				Long facId = Long.parseLong(pageinfo.getCondition().get("facId").toString());
				AgencyVo agencyVo = agencyMapper.selectAgencyInfo(ageId,facId);
				discount = agencyVo.getDiscount();
			}else{
				AgencyUserVo user = (AgencyUserVo) UserUtils.getCurrentUser();
				discount = user.getDiscount();
			}
			Boolean spflag = false;// 用于判断sellproce是否存在
			if(ov.getSellPrice() != null){
					spflag = true;
					ov.setPromotionPrice(ov.getSellPrice());
			}else{
				ov.setSellPrice(ov.getProductPrice());	
				ov.setPromotionPrice(ov.getProductPrice().multiply(
							BigDecimal.valueOf(discount.doubleValue()*0.01)));
			}
			ov.setBasicPrice(ov.getPromotionPrice());
			ov.setSumMoney(ov.getPromotionPrice().multiply(ov.getAmount()));
			resultMap.put(ov.getSkuId(), ov);

			List<ProductMoreUnitEntity> unitlist = morunitMap.get(rs.get(i).getSkuId());
			// 若无数据则添加标准单位
			if(unitlist == null){
				ProductMoreUnitEntity unit2 = new ProductMoreUnitEntity();
				unit2.setUnitId(rs.get(i).getStdUnit());
				unit2.setUnitName(rs.get(i).getStdUnitName());
				unit2.setNum(1);
				unit2.setCustomPrice(ov.getPromotionPrice());
				unitlist = new ArrayList<ProductMoreUnitEntity>();
				unitlist.add(unit2);
			}
			if(rs.get(i).getUnitId() != null){
				ProductMoreUnitEntity unit = new ProductMoreUnitEntity();
				unit.setUnitId(rs.get(i).getUnitId());
				unit.setUnitName(rs.get(i).getUnitName()+"("+rs.get(i).getStdAmount()+rs.get(i).getStdUnitName()+")");
				unit.setNum(rs.get(i).getStdAmount());
				if(spflag == true){
					unit.setCustomPrice(ov.getSellPrice().multiply(new BigDecimal(unit.getNum())));
				}else{
					unit.setCustomPrice(rs.get(i).getCustomPrice().multiply(
							BigDecimal.valueOf(discount.doubleValue()*0.01)));
				}
				unitlist.add(unit);
			}
			ov.setStdAmount(1);
			morunitMap.put(rs.get(i).getSkuId(), unitlist);
		}
		
		// 吧多单位放到sku中
		for(Long skuid : morunitMap.keySet()){
			resultMap.get(skuid).setUnitList(morunitMap.get(skuid));
		}
		
		for(Long skuid : resultMap.keySet()){
			rsresult.add(resultMap.get(skuid));
		}
		pageinfo.setData(rsresult);
	}
}
